import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Button, Input, Toast } from 'antd-mobile'
import styles from '../main/main.module.css'
import { data } from 'react-router-dom'
function Index() {
    const chatEl=useRef(null)
    const [msgVal,setMsgVal]=useState('')
    const [chatList,setchatList]=useState([])
    const user_id=1
    const server_id=4567
    const ws=useMemo(()=>{
        return new WebSocket(
        `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
        )
    },[])
    useEffect(()=>{
      ws.onopen=()=>{
        console.log('链接成功');
        ws.send(JSON.stringify({type:'getChatList'}))
      }
      ws.onmessage=(msg)=>{
        const {type,data}=JSON.parse(msg.data)
        if(type==='getChatList'){
            setchatList(data)
        }else if(type==='addMessage'){
            setchatList(pre=>[...pre,data])
        }
      }  

    },[])
    const handelsel=()=>{
        if(!msgVal) return Toast.show('请输入内容')
            ws.send(JSON.stringify({
        type:'addMessage',
        data:{
           user_id, 
           server_id,
           message:msgVal
        }
        })
   
    )
    setMsgVal('')
    }
    useEffect(()=>{
        if(chatEl.current){
        chatEl.current.scrollTop=10000
        }
    },[chatList])
  return (
    <div className={styles.mainBox} ref={chatEl}>
     <main>
        <div className={styles.chatitem}>
            {
                chatList.map((item,ind)=>{
                     const  Classitem=
                     item.dir ===1?'chat-item-r':'chat-item-l'
                     const diravatar=
                     item.dir ===1?item.user_avatar:item.server.avatar
                     return(
                        <div key={ind} className={styles[Classitem]}>
                            <div>
                                <img src={diravatar} alt="" className={styles.avatar} />
                            </div>
                            <div>
                                <div className={styles.text}>{item.message}</div>
                            </div>
                        
                     </div>
                     )
                })
            }
        </div>
     </main>
     <footer>
          <Input
          placeholder='请输入内容'
          value={msgVal}
          onChange={val => {
            setMsgVal(val)
          }}
        />
        <Button onClick={()=>handelsel()}>发送</Button>

     </footer>
    </div>
  )
}

export default Index
